﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using LeadThing.AbpZeroTemplate.DisputeInformations.Authorization;
using LeadThing.AbpZeroTemplate.DisputeInformations.Dtos;
using LeadThing.AbpZeroTemplate.Dto;
using LeadThing.AbpZeroTemplate.Areas;
using LeadThing.AbpZeroTemplate.DisputeTypes;
using LeadThing.AbpZeroTemplate.WorkFlows;
using LeadThing.AbpZeroTemplate.WorkFlow_Processs;
using LeadThing.AbpZeroTemplate.WorkFlow_Runs;
using LeadThing.AbpZeroTemplate.WorkFlow_Run_Processs;
using Abp.UI;
using Abp.Runtime.Session;
using LeadThing.AbpZeroTemplate.Authorization.Users;
using LeadThing.AbpZeroTemplate.WorkFlow_Run_Processs.Dtos;
using LeadThing.AbpZeroTemplate.WorkFlow_TableNames;
using LeadThing.AbpZeroTemplate.Authorization.Roles;
using LeadThing.AbpZeroTemplate.Authorization.Roles.Dto;
using LeadThing.AbpZeroTemplate.Notifications;
using static LeadThing.AbpZeroTemplate.Configuration.AppSettings;
using LeadThing.AbpZeroTemplate.Map;
using LeadThing.AbpZeroTemplate.Files;
using System.Data.Entity.Core.Objects;
using Abp.Domain.Entities;

namespace LeadThing.AbpZeroTemplate.DisputeInformations
{
    /// <summary>
    /// 矛盾纠纷信息服务实现
    /// </summary>



    public class DisputeInformationAppService : AbpZeroTemplateAppServiceBase, IDisputeInformationAppService
    {
        private readonly IRepository<DisputeInformation, long> _disputeInformationRepository;
        private readonly IDisputeInformationListExcelExporter _disputeInformationListExcelExporter;
        private readonly IRepository<Area, long> _areaRepository;
        private readonly IRepository<DisputeType, long> _disputeTypeRepository;
        private readonly IRepository<User, long> _userRepository;//用户
        private readonly IRoleAppService _roleService;//角色
        private readonly IAppNotifier _appNotifier;//通知
        private readonly IRepository<File, long> _fileRepository;

        //工作流
        private readonly IRepository<WorkFlow, long> _workFlowRepository;//流程表
        private readonly IRepository<WorkFlow_Process, long> _workFlow_ProcessRepository;//流程节点配置表
        private readonly IRepository<WorkFlow_Run, long> _workFlow_RunRepository;//流程实例表
        private readonly IRepository<WorkFlow_Run_Process, long> _workFlow_Run_ProcessRepository;//实例节点流转明细
        private readonly IRepository<WorkFlow_TableName, long> _workFlow_TableNameRepository;



        private readonly DisputeInformationManage _disputeInformationManage;
        private readonly WorkFlowManage _workFlowManage;
        private readonly ISqlExecuter _sqlExecuter;//sql语句接口



        /// <summary>
        /// 构造方法
        /// </summary>
        public DisputeInformationAppService(IRepository<DisputeInformation, long> disputeInformationRepository
      , DisputeInformationManage disputeInformationManage
      , IDisputeInformationListExcelExporter disputeInformationListExcelExporter
      , IRepository<Area, long> areaRepository
      , IRepository<DisputeType, long> disputeTypeRepository
      , IRepository<WorkFlow, long> workFlowRepository
      , IRepository<WorkFlow_Process, long> workFlow_ProcessRepository
      , IRepository<WorkFlow_Run, long> workFlow_RunRepository
      , IRepository<WorkFlow_Run_Process, long> workFlow_Run_ProcessRepository
      , IRepository<WorkFlow_TableName, long> workFlow_TableNameRepository
      , WorkFlowManage workFlowManage
      , IRepository<User, long> userRepository
      , IRoleAppService roleService
      , IAppNotifier appNotifier
      , IRepository<File, long> fileRepository
      , ISqlExecuter sqlExecuter
  )
        {
            _disputeInformationRepository = disputeInformationRepository;
            _disputeInformationManage = disputeInformationManage;
            _disputeInformationListExcelExporter = disputeInformationListExcelExporter;
            _areaRepository = areaRepository;
            _disputeTypeRepository = disputeTypeRepository;
            _workFlowRepository = workFlowRepository;
            _workFlow_ProcessRepository = workFlow_ProcessRepository;
            _workFlow_RunRepository = workFlow_RunRepository;
            _workFlow_Run_ProcessRepository = workFlow_Run_ProcessRepository;
            _workFlow_TableNameRepository = workFlow_TableNameRepository;
            _workFlowManage = workFlowManage;
            _userRepository = userRepository;
            _roleService = roleService;
            _appNotifier = appNotifier;
            _fileRepository = fileRepository;
            _sqlExecuter = sqlExecuter;
        }


        #region 实体的自定义扩展方法
        private IQueryable<DisputeInformation> _disputeInformationRepositoryAsNoTrack => _disputeInformationRepository.GetAll().AsNoTracking();


        /// <summary>
        /// 催办
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task Reminders(RemindersEditDto input)
        {
            var userModel = _userRepository.FirstOrDefault(input.UserID);
            EntityIdentifier entityModel = new EntityIdentifier(typeof(DisputeInformation), input.Id);
            SentFrendshipRequestNotificationData model = new SentFrendshipRequestNotificationData() { MessageContent = input.Remark, User = userModel, EntityIdentifier = entityModel };
            await _appNotifier.NewNoticeAsync(model);
        }

        /// <summary>
        /// 根据查询条件获取矛盾纠纷信息分页列表（跟踪督办）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<DisputeInformationListDto>> GetPagedDisputeInformationsGzdbAsync(GetDisputeInformationInput input)
        {

            StringBuilder sb = new StringBuilder();

            var query = _disputeInformationRepositoryAsNoTrack;

            //已结案的不显示
            query = query.Where(p => p.Status != 6 && p.Status != 7);

            #region TODO:根据传入的参数添加过滤条件

            //TODO:根据传入的参数添加过滤条件

            #region 权限验证

            var userID = AbpSession.GetUserId();
            var userModel = _userRepository.FirstOrDefault(userID);
            GetRolesInput input_role = new GetRolesInput() { UserId = userID };
            var role = await _roleService.GetRolesByUserId(input_role);

            if (role.DisplayName == "乡镇网格管理员")
                query = query.Where(p => p.TownID == userModel.TownID || p.CreatorUserId == userID);
            else if (role.DisplayName == "社区网格管理员")
                query = query.Where(p => p.AreaID == userModel.AreaID || p.CreatorUserId == userID);
            else if (role.DisplayName == "村庄网格管理员")
                query = query.Where(p => p.VillageID == userModel.VillageID || p.CreatorUserId == userID);

            #endregion

            if (!string.IsNullOrWhiteSpace(input.Filter))
                query = query.Where(p => p.UploadName.Contains(input.Filter));

            if (input.Status != 0)
            {
                if (input.endStaus != 0)
                    query = query.Where(p => p.Status == input.Status || p.Status == input.endStaus);
                else
                    query = query.Where(p => p.Status == input.Status);
            }

            //上传人
            if (!string.IsNullOrWhiteSpace(input.UploadName))
                query = query.Where(p => p.UploadName == input.UploadName);

            //当事人
            if (!string.IsNullOrWhiteSpace(input.Party))
                query = query.Where(p => p.Party == input.Party);

            //日期范围
            if (!string.IsNullOrWhiteSpace(input.StartDate) && !string.IsNullOrWhiteSpace(input.EndDate))
            {
                var startDate = Convert.ToDateTime(Convert.ToDateTime(input.StartDate).ToShortDateString());
                var endDate = Convert.ToDateTime(Convert.ToDateTime(input.EndDate).ToShortDateString());
                query = query.Where(p => p.CreationTime >= startDate && p.CreationTime <= endDate);
            }


            //镇
            if (input.TownID != 0)
                query = query.Where(p => p.TownID == input.TownID);

            //区
            if (input.AreaID != 0)
                query = query.Where(p => p.AreaID == input.AreaID);

            //村庄
            if (input.VillageID != 0)
                query = query.Where(p => p.VillageID == input.VillageID);

            #endregion

            var disputeInformationCount = await query.CountAsync();

            var disputeInformations = await query
            .OrderByDescending(p => p.Id)
            .PageBy(input)
            .ToListAsync();

            var areaList = _areaRepository.GetAll();
            var disputeTypeList = _disputeTypeRepository.GetAll();
            var disSourceList = GetAllDisSourceList();

            var workflowList = from wf_run in _workFlow_RunRepository.GetAll()
                               join wf_run_process in _workFlow_Run_ProcessRepository.GetAll()
                               on wf_run.Id equals wf_run_process.RunID
                               select new { wf_run.DetailID, wf_run_process.ProcessType };

            var wfProcessList = (from wfProcess in _workFlow_ProcessRepository.GetAll()
                                 join wfTableName in _workFlow_TableNameRepository.GetAll()
                                 on wfProcess.FlowID equals wfTableName.Id
                                 where wfTableName.TableName == "DisputeInformations"
                                 select wfProcess).ToList();

            var nowDate = DateTime.Now;

            return new PagedResultDto<DisputeInformationListDto>(disputeInformationCount,
                disputeInformations.Select(item =>
                {
                    var dto = item.MapTo<DisputeInformationListDto>();

                    var sID = dto.SourceID.ToString();
                    var disSourceModel = disSourceList.Where(p => p.Value == sID).Select(p => new { p.DisplayText }).FirstOrDefault();
                    if (disSourceModel != null)
                        dto.SourceTitle = disSourceModel.DisplayText;

                    var disputeTypeModel = disputeTypeList.Where(p => p.Id == dto.DisputeTypeID).Select(p => new { p.Title }).FirstOrDefault();
                    if (disputeTypeModel != null)
                        dto.DisputeTypeTitle = disputeTypeModel.Title;

                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    var wfList = workflowList.Where(p => p.DetailID == dto.Id && p.ProcessType == "is_end").ToList();
                    if (wfList.Count > 0)
                        dto.ShowMenu = false;
                    else
                        dto.ShowMenu = true;

                    if (wfProcessList.Count > 0)
                    {
                        var endModel = wfProcessList.Where(p => p.ProcessType == "is_end").FirstOrDefault();
                        var failModel = wfProcessList.Where(p => p.ProcessType == "is_fail").FirstOrDefault();

                        if (nowDate >= dto.CreationTime.AddMonths(1) && dto.Status != endModel.Id && dto.Status != failModel.Id)
                            dto.ChaoQi = "seleted";
                        else
                            dto.ChaoQi = "";

                        var proModel = wfProcessList.Where(p => p.Id == dto.Status).FirstOrDefault();
                        if (proModel != null)
                        {
                            dto.StatusName = proModel.ProcessName;
                        }
                    }

                    return dto;
                }).ToList());
        }


        /// <summary>
        /// 根据查询条件获取矛盾纠纷信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResultDto<DisputeInformationListDto>> GetDisputeInformationsByWhereAsync(GetDisputeInformationInput input)
        {
            var query = _disputeInformationRepositoryAsNoTrack;

            //TODO:根据传入的参数添加过滤条件
            #region 根据传入的参数添加过滤条件

            #region 权限验证

            var userID = AbpSession.GetUserId();
            var userModel = _userRepository.FirstOrDefault(userID);
            GetRolesInput input_role = new GetRolesInput() { UserId = userID };
            var role = await _roleService.GetRolesByUserId(input_role);

            if (role.DisplayName == "乡镇网格管理员")
                query = query.Where(p => p.TownID == userModel.TownID || p.CreatorUserId == userID);
            else if (role.DisplayName == "社区网格管理员")
                query = query.Where(p => p.AreaID == userModel.AreaID || p.CreatorUserId == userID);
            else if (role.DisplayName == "村庄网格管理员")
                query = query.Where(p => p.VillageID == userModel.VillageID || p.CreatorUserId == userID);

            #endregion


            #endregion

            var items = await query.ToListAsync();

            var areaList = _areaRepository.GetAll();
            var disputeTypeList = _disputeTypeRepository.GetAll();
            var disSourceList = GetAllDisSourceList();

            return new ListResultDto<DisputeInformationListDto>(
                items.Select(item =>
                {
                    var dto = item.MapTo<DisputeInformationListDto>();

                    var sID = dto.SourceID.ToString();
                    var disSourceModel = disSourceList.Where(p => p.Value == sID).Select(p => new { p.DisplayText }).FirstOrDefault();
                    if (disSourceModel != null)
                        dto.SourceTitle = disSourceModel.DisplayText;

                    var disputeTypeModel = disputeTypeList.Where(p => p.Id == dto.DisputeTypeID).Select(p => new { p.Title }).FirstOrDefault();
                    if (disputeTypeModel != null)
                        dto.DisputeTypeTitle = disputeTypeModel.Title;

                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 获取所有纠纷来源
        /// </summary>
        /// <returns></returns>
        public List<ComboboxItemDto> GetAllDisSourceList()
        {
            return _disputeInformationManage.GetAllDisSourceList();
        }

        /// <summary>
        /// 获取所有紧急程度
        /// </summary>
        /// <returns></returns>
        public List<ComboboxItemDto> GetAllDisUrgencyList()
        {
            return _disputeInformationManage.GetAllDisUrgencyList();
        }

        /// <summary>
        /// 获取所有流程节点
        /// </summary>
        /// <returns></returns>
        public List<ComboboxItemDto> GetAllWorkFlowProcesssList(NullableIdDto<long> input)
        {
            var query = _workFlow_ProcessRepository.GetAll();
            if (input != null)
            {
                query = query.Where(w => w.FlowID == input.Id);
            }

            var list = new List<ComboboxItemDto>();
            var processs = query.ToList();
            foreach (var process in processs)
            {
                list.Add(new ComboboxItemDto() { Value = process.Id.ToString(), DisplayText = process.ProcessName });
            }
            return list;
        }


        /// <summary>
        /// 新增或更改矛盾纠纷信息（公共方法）
        /// </summary>
        public async Task CreateOrUpdateDisputeInformationCommonAsync(CreateOrUpdateDisputeInformationInput input)
        {
            if (input.DisputeInformationEditDto.Id.HasValue)
            {
                await UpdateDisputeInformationCommonAsync(input.DisputeInformationEditDto);
            }
            else
            {
                await CreateDisputeInformationCommonAsync(input.DisputeInformationEditDto);
            }
        }

        /// <summary>
        /// 新增矛盾纠纷信息（公共方法）
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation_CreateDisputeInformation)]
        public virtual async Task<DisputeInformationEditDto> CreateDisputeInformationCommonAsync(DisputeInformationEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<DisputeInformation>();

            entity = await _disputeInformationRepository.InsertAsync(entity);
            return entity.MapTo<DisputeInformationEditDto>();
        }

        /// <summary>
        /// 编辑矛盾纠纷信息（公共方法）
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation_EditDisputeInformation)]
        public virtual async Task UpdateDisputeInformationCommonAsync(DisputeInformationEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _disputeInformationRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _disputeInformationRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 统计平安无事
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResultDto<object>> GetPingAnWuShi(GetDisputeInformationInput input)
        {
            var query = _disputeInformationRepositoryAsNoTrack;
            var areaList = _areaRepository.GetAll();

            //纠纷类别是平安无事的ID:16
            query = query.Where(p => p.DisputeTypeID == 16);

            #region TODO:根据传入的参数添加过滤条件

            //日期范围
            if (!string.IsNullOrWhiteSpace(input.StartDate) && !string.IsNullOrWhiteSpace(input.EndDate))
            {
                var startDate = Convert.ToDateTime(Convert.ToDateTime(input.StartDate).ToShortDateString());
                var endDate = Convert.ToDateTime(Convert.ToDateTime(input.EndDate).ToShortDateString());
                query = query.Where(p => p.CreationTime >= startDate && p.CreationTime <= endDate);
            }

            #endregion

            var list = from table in query
                       group table by new { table.TownID, table.AreaID, table.VillageID, table.UploadName } into g
                       select new
                       {
                           TownTitle = (from areaTable in areaList where areaTable.Id == g.Key.TownID select areaTable.Title).FirstOrDefault(),
                           AreaTitle = (from areaTable in areaList where areaTable.Id == g.Key.AreaID select areaTable.Title).FirstOrDefault(),
                           VillageTitle = (from areaTable in areaList where areaTable.Id == g.Key.VillageID select areaTable.Title).FirstOrDefault(),
                           g.Key.UploadName,
                           CreateTime = (from table in query where table.TownID == g.Key.TownID && table.AreaID == g.Key.AreaID && table.VillageID == g.Key.VillageID && table.UploadName == g.Key.UploadName orderby table.CreationTime descending select table.CreationTime).FirstOrDefault(),
                           CountDis = g.Count()
                       };

            var items = await list.ToListAsync();
            return new ListResultDto<object>(
                items.Select(item =>
                {
                    var dto = item;
                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 获取时间统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResultDto<TimeStatisticsListDto>> GetTimeStatistics(GetDisputeInformationInput input)
        {
            var query = _disputeInformationRepositoryAsNoTrack;
            var areaList = _areaRepository.GetAll();

            #region TODO:根据传入的参数添加过滤条件

            //日期范围
            if (!string.IsNullOrWhiteSpace(input.StartDate) && !string.IsNullOrWhiteSpace(input.EndDate))
            {
                var startDate = Convert.ToDateTime(Convert.ToDateTime(input.StartDate).ToShortDateString());
                var endDate = Convert.ToDateTime(Convert.ToDateTime(input.EndDate).ToShortDateString());
                query = query.Where(p => p.CreationTime >= startDate && p.CreationTime <= endDate);
            }

            #endregion

            var one = from infor in query
                      join area in areaList
                      on infor.AreaID equals area.Id
                      group area by new { area.Id, area.Title } into g
                      select new { g.Key.Id, g.Key.Title };

            var tow = from area in one
                      select new
                      {
                          area.Id,
                          area.Title,
                          ShouLi = (from infor in query
                                    where infor.AreaID == area.Id && infor.Status == 2
                                    select infor).Count(),
                          FenLiu = (from infor in query
                                    where infor.AreaID == area.Id && infor.Status == 3
                                    select infor).Count(),
                          TiaoJie = (from infor in query
                                     where infor.AreaID == area.Id && infor.Status == 4
                                     select infor).Count(),
                          DuBan = (from infor in query
                                   where infor.AreaID == area.Id && infor.Status == 5
                                   select infor).Count(),
                          HuiFang = (from infor in query
                                     where infor.AreaID == area.Id && infor.Status == 6
                                     select infor).Count(),
                          JieAn = (from infor in query
                                   where infor.AreaID == area.Id && infor.Status == 7
                                   select infor).Count(),
                          QiTaQuDao = (from infor in query
                                       where infor.AreaID == area.Id && infor.Status == 7
                                       select infor).Count()
                      };


            var items = await tow.ToListAsync();
            return new ListResultDto<TimeStatisticsListDto>(
                items.Select(item =>
                {
                    var dto = new TimeStatisticsListDto();

                    dto.Id = item.Id;
                    dto.Title = item.Title;
                    dto.ShouLi = item.ShouLi;
                    dto.FenLiu = item.FenLiu;
                    dto.TiaoJie = item.TiaoJie;
                    dto.DuBan = item.DuBan;
                    dto.HuiFang = item.HuiFang;
                    dto.JieAn = item.JieAn;
                    dto.QiTaQuDao = item.QiTaQuDao;

                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 获取柱状图数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResultDto<object>> GetBarChart()
        {
            var query = _disputeInformationRepositoryAsNoTrack;
            var disputeTypeList = _disputeTypeRepository.GetAll();

            var list = from dtype in disputeTypeList
                       join dis in query
                       on dtype.Id equals dis.DisputeTypeID into temp
                       from tt in temp.DefaultIfEmpty()
                       group dtype by new { dtype.Id, dtype.Title } into g
                       select new
                       {
                           x = g.Key.Title,
                           y = (from dis in query where dis.DisputeTypeID == g.Key.Id select dis).Count()
                       };

            var items = await list.ToListAsync();
            return new ListResultDto<object>(
                items.Select(item =>
                {
                    var dto = item;
                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 获取饼图数据
        /// </summary>
        /// <returns></returns>
        public async Task<ListResultDto<object>> GetPie()
        {
            var query = _disputeInformationRepositoryAsNoTrack;
            var disputeTypeList = _disputeTypeRepository.GetAll();

            var list = from dtype in disputeTypeList
                       join dis in query
                       on dtype.Id equals dis.DisputeTypeID into temp
                       from tt in temp.DefaultIfEmpty()
                       group dtype by new { dtype.Id, dtype.Title } into g
                       select new
                       {
                           x = g.Key.Title,
                           y = Math.Round((((Double)(from dis in query where dis.DisputeTypeID == g.Key.Id select dis).Count() / (Double)(query.Count())) * 100), 2)
                       };

            var items = await list.ToListAsync();
            return new ListResultDto<object>(
                items.Select(item =>
                {
                    var dto = item;
                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 获取各种类型纠纷在各乡镇中的占比
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ListResultDto<object>> GetTownPie(GetDisputeInformationInput input)
        {
            var query = _disputeInformationRepositoryAsNoTrack;

            var newQuery = _disputeInformationRepository.GetAll();

            #region TODO:根据传入的参数添加过滤条件

            //镇
            if (input.DisputeTypeID != 0)
                query = query.Where(p => p.DisputeTypeID == input.DisputeTypeID);

            #endregion

            var areaList = _areaRepository.GetAll();
            //只取乡镇一级
            areaList = areaList.Where(p => p.Level == 1);

            var list = from area in areaList
                       join dis in query
                       on area.Id equals dis.DisputeTypeID into temp
                       from tt in temp.DefaultIfEmpty()
                       group area by new { area.Id, area.Title } into g
                       select new
                       {
                           x = g.Key.Title,
                           y = Math.Round((((Double)(from dis in query where dis.TownID == g.Key.Id select dis).Count() / (Double)(newQuery.Count())) * 100), 2),
                           z = (from dis in query where dis.TownID == g.Key.Id select dis).Count()
                       };

            var items = await list.ToListAsync();
            return new ListResultDto<object>(
                items.Select(item =>
                {
                    var dto = item;
                    return dto;
                }).ToList());
        }

        #endregion


        #region 矛盾纠纷信息管理

        /// <summary>
        /// 根据查询条件获取矛盾纠纷信息分页列表（无数据权限）
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation)]
        public async Task<PagedResultDto<DisputeInformationListDto>> GetPagedDisputeInformationsNoUserAsync(GetDisputeInformationInput input)
        {

            var query = _disputeInformationRepositoryAsNoTrack;

            #region TODO:根据传入的参数添加过滤条件

            //TODO:根据传入的参数添加过滤条件

            #region 权限验证

            var userID = AbpSession.GetUserId();
            var userModel = _userRepository.FirstOrDefault(userID);
            GetRolesInput input_role = new GetRolesInput() { UserId = userID };
            var role = await _roleService.GetRolesByUserId(input_role);

            if (role.DisplayName == "乡镇网格管理员")
                query = query.Where(p => p.TownID == userModel.TownID || p.CreatorUserId == userID);
            else if (role.DisplayName == "社区网格管理员")
                query = query.Where(p => p.AreaID == userModel.AreaID || p.CreatorUserId == userID);
            else if (role.DisplayName == "村庄网格管理员")
                query = query.Where(p => p.VillageID == userModel.VillageID || p.CreatorUserId == userID);

            #endregion

            if (!string.IsNullOrWhiteSpace(input.Filter))
                query = query.Where(p => p.UploadName.Contains(input.Filter));

            if (input.Status != 0)
            {
                if (input.endStaus != 0)
                    query = query.Where(p => p.Status == input.Status || p.Status == input.endStaus);
                else
                    query = query.Where(p => p.Status == input.Status);
            }

            //上传人
            if (!string.IsNullOrWhiteSpace(input.UploadName))
                query = query.Where(p => p.UploadName == input.UploadName);

            //当事人
            if (!string.IsNullOrWhiteSpace(input.Party))
                query = query.Where(p => p.Party == input.Party);

            //日期范围
            if (!string.IsNullOrWhiteSpace(input.StartDate) && !string.IsNullOrWhiteSpace(input.EndDate))
            {
                var startDate = Convert.ToDateTime(Convert.ToDateTime(input.StartDate).ToShortDateString());
                var endDate = Convert.ToDateTime(Convert.ToDateTime(input.EndDate).ToShortDateString());
                query = query.Where(p => p.CreationTime >= startDate && p.CreationTime <= endDate);
            }


            //镇
            if (input.TownID != 0)
                query = query.Where(p => p.TownID == input.TownID);

            //区
            if (input.AreaID != 0)
                query = query.Where(p => p.AreaID == input.AreaID);

            //村庄
            if (input.VillageID != 0)
                query = query.Where(p => p.VillageID == input.VillageID);

            #endregion

            var disputeInformationCount = await query.CountAsync();

            var disputeInformations = await query
            .OrderByDescending(p => p.Id)
            .PageBy(input)
            .ToListAsync();

            var areaList = _areaRepository.GetAll();
            var disputeTypeList = _disputeTypeRepository.GetAll();
            var disSourceList = GetAllDisSourceList();

            var workflowList = from wf_run in _workFlow_RunRepository.GetAll()
                               join wf_run_process in _workFlow_Run_ProcessRepository.GetAll()
                               on wf_run.Id equals wf_run_process.RunID
                               select new { wf_run.DetailID, wf_run_process.ProcessType };

            var workflowprocess = _workFlow_ProcessRepository.GetAll();

            return new PagedResultDto<DisputeInformationListDto>(disputeInformationCount,
                disputeInformations.Select(item =>
                {
                    var dto = item.MapTo<DisputeInformationListDto>();

                    var sID = dto.SourceID.ToString();
                    var disSourceModel = disSourceList.Where(p => p.Value == sID).Select(p => new { p.DisplayText }).FirstOrDefault();
                    if (disSourceModel != null)
                        dto.SourceTitle = disSourceModel.DisplayText;

                    var disputeTypeModel = disputeTypeList.Where(p => p.Id == dto.DisputeTypeID).Select(p => new { p.Title }).FirstOrDefault();
                    if (disputeTypeModel != null)
                        dto.DisputeTypeTitle = disputeTypeModel.Title;

                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    var wfList = workflowList.Where(p => p.DetailID == dto.Id && p.ProcessType == "is_end").ToList();
                    if (wfList.Count > 0)
                        dto.ShowMenu = false;
                    else
                        dto.ShowMenu = true;

                    var currentProcess = workflowprocess.Where(p => p.Id == dto.Status).FirstOrDefault();
                    if (currentProcess != null)
                        dto.CurrentProcessName = currentProcess.ProcessName;

                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 根据查询条件获取矛盾纠纷信息分页列表
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation)]
        public async Task<PagedResultDto<DisputeInformationListDto>> GetPagedDisputeInformationsAsync(GetDisputeInformationInput input)
        {

            var query = _disputeInformationRepositoryAsNoTrack;

            #region TODO:根据传入的参数添加过滤条件

            //TODO:根据传入的参数添加过滤条件

            #region 权限验证

            var userID = AbpSession.GetUserId();
            var userModel = _userRepository.FirstOrDefault(userID);
            GetRolesInput input_role = new GetRolesInput() { UserId = userID };
            var role = await _roleService.GetRolesByUserId(input_role);

            if (role.DisplayName == "乡镇网格管理员")
                query = query.Where(p => p.TownID == userModel.TownID || p.CreatorUserId == userID);
            else if (role.DisplayName == "社区网格管理员")
                query = query.Where(p => p.AreaID == userModel.AreaID || p.CreatorUserId == userID);
            else if (role.DisplayName == "村庄网格管理员")
                query = query.Where(p => p.VillageID == userModel.VillageID || p.CreatorUserId == userID);

            #endregion

            if (!string.IsNullOrWhiteSpace(input.Filter))
                query = query.Where(p => p.UploadName.Contains(input.Filter));

            if (input.Status != 0)
            {
                if (input.endStaus != 0)
                    query = query.Where(p => p.Status == input.Status || p.Status == input.endStaus);
                else
                    query = query.Where(p => p.Status == input.Status);
            }

            //上传人
            if (!string.IsNullOrWhiteSpace(input.UploadName))
                query = query.Where(p => p.UploadName == input.UploadName);

            //当事人
            if (!string.IsNullOrWhiteSpace(input.Party))
                query = query.Where(p => p.Party == input.Party);

            //日期范围
            if (!string.IsNullOrWhiteSpace(input.StartDate) && !string.IsNullOrWhiteSpace(input.EndDate))
            {
                var startDate = Convert.ToDateTime(Convert.ToDateTime(input.StartDate).ToShortDateString());
                var endDate = Convert.ToDateTime(Convert.ToDateTime(input.EndDate).ToShortDateString());
                query = query.Where(p => p.CreationTime >= startDate && p.CreationTime <= endDate);
            }


            //镇
            if (input.TownID != 0)
                query = query.Where(p => p.TownID == input.TownID);

            //区
            if (input.AreaID != 0)
                query = query.Where(p => p.AreaID == input.AreaID);

            //村庄
            if (input.VillageID != 0)
                query = query.Where(p => p.VillageID == input.VillageID);


            //纠纷分类
            if (input.DisputeTypeID != null && input.DisputeTypeID != 0)
                query = query.Where(p => p.DisputeTypeID == input.DisputeTypeID);

            //纠纷来源
            if (input.SourceID != null && input.SourceID != 0)
                query = query.Where(p => p.SourceID == input.SourceID);

            //流程状态
            if (input.CurrentProcessID != null && input.CurrentProcessID != 0)
                query = query.Where(p => p.Status == input.CurrentProcessID);
            #endregion

            var disputeInformationCount = await query.CountAsync();

            var disputeInformations = await query
            .OrderByDescending(p => p.Id)
            .PageBy(input)
            .ToListAsync();

            var areaList = _areaRepository.GetAll();
            var disputeTypeList = _disputeTypeRepository.GetAll();
            var disSourceList = GetAllDisSourceList();

            var workflowList = from wf_run in _workFlow_RunRepository.GetAll()
                               join wf_run_process in _workFlow_Run_ProcessRepository.GetAll()
                               on wf_run.Id equals wf_run_process.RunID
                               select new { wf_run.DetailID, wf_run_process.ProcessType };

            var workflowprocess = _workFlow_ProcessRepository.GetAll();

            return new PagedResultDto<DisputeInformationListDto>(disputeInformationCount,
                disputeInformations.Select(item =>
                {
                    var dto = item.MapTo<DisputeInformationListDto>();

                    var sID = dto.SourceID.ToString();
                    var disSourceModel = disSourceList.Where(p => p.Value == sID).Select(p => new { p.DisplayText }).FirstOrDefault();
                    if (disSourceModel != null)
                        dto.SourceTitle = disSourceModel.DisplayText;

                    var disputeTypeModel = disputeTypeList.Where(p => p.Id == dto.DisputeTypeID).Select(p => new { p.Title }).FirstOrDefault();
                    if (disputeTypeModel != null)
                        dto.DisputeTypeTitle = disputeTypeModel.Title;

                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    var wfList = workflowList.Where(p => p.DetailID == dto.Id && p.ProcessType == "is_end").ToList();
                    if (wfList.Count > 0)
                        dto.ShowMenu = false;
                    else
                        dto.ShowMenu = true;

                    var currentProcess = workflowprocess.Where(p => p.Id == dto.Status).FirstOrDefault();
                    if (currentProcess != null)
                        dto.CurrentProcessName = currentProcess.ProcessName;

                    return dto;
                }).ToList());
        }
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation)]
        public async Task<PagedResultDto<DisputeCountListDto>> GetPagedDisputeInformationsCountByGroup(GetDisputeInformationInput input)
        {
            var scerachId = 0;
            var type = "TownID";
            //镇
            if (input.TownID > 0) scerachId = input.TownID;
            //区
            if (input.AreaID > 0)
            {
                scerachId = input.AreaID;
                type = "AreaID";
            }
            //村庄
            if (input.VillageID > 0)
            {
                scerachId = input.VillageID;
                type = "VillageID";
            }

            var areaQuery = _areaRepository.GetAll();
            var areaList = areaQuery.Where(a => a.ParentId == scerachId).ToList();
            if (areaList.Count == 0)
                areaList = areaQuery.Where(a => a.Id == scerachId).ToList();

            var areaIds = areaList.Select(a => a.Id).ToList();
            
            var resultList = new List<DisputeCountListDto>(areaIds.Count);
            foreach (var area in areaList) {

                var query = _disputeInformationRepository.GetAll();
                #region MyRegion
                if (!string.IsNullOrWhiteSpace(input.Filter))
                    query = query.Where(p => p.UploadName.Contains(input.Filter));

                if (input.Status != 0)
                {
                    if (input.endStaus != 0)
                        query = query.Where(p => p.Status == input.Status || p.Status == input.endStaus);
                    else
                        query = query.Where(p => p.Status == input.Status);
                }

                //上传人
                if (!string.IsNullOrWhiteSpace(input.UploadName))
                    query = query.Where(p => p.UploadName == input.UploadName);

                //当事人
                if (!string.IsNullOrWhiteSpace(input.Party))
                    query = query.Where(p => p.Party == input.Party);

                //日期范围
                if (!string.IsNullOrWhiteSpace(input.StartDate) && !string.IsNullOrWhiteSpace(input.EndDate))
                {
                    var startDate = Convert.ToDateTime(Convert.ToDateTime(input.StartDate).ToShortDateString());
                    var endDate = Convert.ToDateTime(Convert.ToDateTime(input.EndDate).ToShortDateString());
                    query = query.Where(p => p.CreationTime >= startDate && p.CreationTime <= endDate);
                }
                //纠纷分类
                if (input.DisputeTypeID != null && input.DisputeTypeID != 0)
                    query = query.Where(p => p.DisputeTypeID == input.DisputeTypeID);

                //纠纷来源
                if (input.SourceID != null && input.SourceID != 0)
                    query = query.Where(p => p.SourceID == input.SourceID);

                //流程状态
                if (input.CurrentProcessID != null && input.CurrentProcessID != 0)
                    query = query.Where(p => p.Status == input.CurrentProcessID);
                #endregion
                DisputeCountListDto res = new DisputeCountListDto { Id = area.Id, Name = area.Title };
                if (scerachId > 0)
                {
                    if (type == "TownID")
                        res.Count = await query.CountAsync(u => u.TownID == input.TownID && u.AreaID == area.Id);
                    else if (type == "AreaID" || type == "VillageID")
                        res.Count = await query.CountAsync(u => u.TownID == input.TownID && u.AreaID == input.AreaID && u.VillageID == area.Id);
                }
                else
                    res.Count = await query.CountAsync(u => u.TownID == area.Id);

                resultList.Add(res);
            }
            return new PagedResultDto<DisputeCountListDto>(areaIds.Count, resultList); ;
        }



        /// <summary>
        /// 通过Id获取矛盾纠纷信息信息进行编辑或修改 
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation)]
        public async Task<GetDisputeInformationForEditOutput> GetDisputeInformationForEditAsync(NullableIdDto<long> input)
        {
            var output = new GetDisputeInformationForEditOutput();

            DisputeInformationEditDto disputeInformationEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _disputeInformationRepository.GetAsync(input.Id.Value);

                var resultModel = entity.MapTo<DisputeInformationEditDto>();

                var areaList = _areaRepository.GetAll();

                var townModel = areaList.Where(p => p.Id == entity.TownID).Select(p => new { p.Title }).FirstOrDefault();
                if (townModel != null)
                    resultModel.TownTitle = townModel.Title;

                var areaModel = areaList.Where(p => p.Id == entity.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                if (areaModel != null)
                    resultModel.AreaTitle = areaModel.Title;

                var villModel = areaList.Where(p => p.Id == entity.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                if (villModel != null)
                    resultModel.VillageTitle = villModel.Title;

                var userModel = _userRepository.GetAll().Where(p => p.Id == entity.UserID).FirstOrDefault();
                if (userModel != null)
                    resultModel.ClientID = userModel.ClientID;

                //var EventDescImgModel = _fileRepository.GetAll().Where(p => p.Id == entity.EventDescImgID).FirstOrDefault();
                //if (EventDescImgModel != null)
                //    resultModel.EventDescImgUrl = AppSetting.AppUrl + EventDescImgModel.Url;

                disputeInformationEditDto = resultModel;
            }
            else
            {
                disputeInformationEditDto = new DisputeInformationEditDto();
            }

            output.DisputeInformation = disputeInformationEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取矛盾纠纷信息ListDto信息
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation)]
        public async Task<DisputeInformationListDto> GetDisputeInformationByIdAsync(EntityDto<long> input)
        {
            var entity = await _disputeInformationRepository.GetAsync(input.Id);

            return entity.MapTo<DisputeInformationListDto>();
        }







        /// <summary>
        /// 新增或更改矛盾纠纷信息
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation)]
        public async Task CreateOrUpdateDisputeInformationAsync(CreateOrUpdateDisputeInformationInput input)
        {
            if (input.DisputeInformationEditDto.Id.HasValue)
            {
                await UpdateDisputeInformationAsync(input.DisputeInformationEditDto);
            }
            else
            {
                await CreateDisputeInformationAsync(input.DisputeInformationEditDto);
            }
        }

        /// <summary>
        /// 新增矛盾纠纷信息
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation_CreateDisputeInformation)]
        public virtual async Task<DisputeInformationEditDto> CreateDisputeInformationAsync(DisputeInformationEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<DisputeInformation>();

            #region 获取发起节点ID
            //获取发起节点ID
            var query = from process in _workFlow_ProcessRepository.GetAll()
                        join table in _workFlow_TableNameRepository.GetAll()
                        on process.TableID equals table.Id
                        where table.TableName == "DisputeInformations"
                        select new { process.Id, process.ProcessOrder, process.TableID, process.FlowID };

            var wf_ProcessModel = query.OrderBy(p => p.ProcessOrder).FirstOrDefault();
            #endregion

            entity.Status = Convert.ToInt32(wf_ProcessModel.Id);//赋值发起节点ID

            //先执行新增纠纷操作
            entity.Id = await _disputeInformationRepository.InsertAndGetIdAsync(entity);

            //添加工作流
            _workFlowManage.AuditStart(Convert.ToInt32(entity.Id), Convert.ToInt32(wf_ProcessModel.Id), "发起一个纠纷事件", Convert.ToInt32(wf_ProcessModel.Id), wf_ProcessModel.FlowID);

            return entity.MapTo<DisputeInformationEditDto>();
        }

        /// <summary>
        /// 编辑矛盾纠纷信息
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation_EditDisputeInformation)]
        public virtual async Task UpdateDisputeInformationAsync(DisputeInformationEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _disputeInformationRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            #region 获取当前节点的下一节点
            //获取当前节点的下一节点
            var wfProcess = _workFlow_ProcessRepository;
            var wf_ProcessModel = wfProcess.FirstOrDefault(entity.Status);
            #endregion

            #region 获取FlowID
            //获取FlowID
            var query = from process in _workFlow_ProcessRepository.GetAll()
                        join table in _workFlow_TableNameRepository.GetAll()
                        on process.TableID equals table.Id
                        where table.TableName == "DisputeInformations"
                        select new { process.Id, process.ProcessOrder, process.TableID, process.FlowID };
            var wfProcessNewModel = query.FirstOrDefault();
            #endregion

            if (input.ProcessContent == "进行纠纷事件失败处理" || input.ProcessContent == "进行纠纷事件拒签处理" || input.ProcessContent == "进行纠纷事件未履行")
            {
                var failModel = wfProcess.GetAll().Where(p => p.FlowID == wfProcessNewModel.FlowID && p.ProcessType == "is_fail").FirstOrDefault();

                //添加工作流
                _workFlowManage.AuditStart(Convert.ToInt32(entity.Id), entity.Status, input.ProcessContent, Convert.ToInt32(failModel.Id), wfProcessNewModel.FlowID);
                entity.Status = Convert.ToInt32(failModel.Id);//赋值失败节点ID
            }
            else
            {
                //添加工作流
                _workFlowManage.AuditStart(Convert.ToInt32(entity.Id), entity.Status, input.ProcessContent, Convert.ToInt32(wf_ProcessModel.ProcessTo), wfProcessNewModel.FlowID);
                entity.Status = Convert.ToInt32(wf_ProcessModel.ProcessTo);//赋值下一节点ID
            }

            await _disputeInformationRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除矛盾纠纷信息
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation_DeleteDisputeInformation)]
        public async Task DeleteDisputeInformationAsync(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _disputeInformationRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除矛盾纠纷信息
        /// </summary>
        [AbpAuthorize(DisputeInformationAppPermissions.DisputeInformation_DeleteDisputeInformation)]
        public async Task BatchDeleteDisputeInformationAsync(List<long> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _disputeInformationRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion

        #region 矛盾纠纷信息的Excel导出功能

        public async Task<FileDto> GetDisputeInformationToExcel()
        {
            var entities = await _disputeInformationRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<DisputeInformationListDto>>();

            var fileDto = _disputeInformationListExcelExporter.ExportDisputeInformationToFile(dtos);



            return fileDto;
        }

        #endregion

        #region APP接口

        /// <summary>
        /// 通过Id获取矛盾纠纷信息信息进行编辑或修改 
        /// </summary>
        public async Task<DisputeInformationAPPEditDto> GetDisputeInformationForAPPEditAsync(EntityDto<string> input)
        {
            DisputeInformationAPPEditDto disputeInformationEditDto;

            if (!string.IsNullOrWhiteSpace(input.Id))
            {
                var id = Convert.ToInt32(input.Id);
                var entity = await _disputeInformationRepository.GetAsync(id);

                var resultModel = entity.MapTo<DisputeInformationAPPEditDto>();

                var areaList = _areaRepository.GetAll();

                var townModel = areaList.Where(p => p.Id == entity.TownID).Select(p => new { p.Title }).FirstOrDefault();
                if (townModel != null)
                    resultModel.TownTitle = townModel.Title;

                var areaModel = areaList.Where(p => p.Id == entity.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                if (areaModel != null)
                    resultModel.AreaTitle = areaModel.Title;

                var villModel = areaList.Where(p => p.Id == entity.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                if (villModel != null)
                    resultModel.VillageTitle = villModel.Title;

                var _sourceID = entity.SourceID.ToString();
                var sourceModel = _disputeInformationManage.GetAllDisSourceList().Where(p => p.Value == _sourceID).FirstOrDefault();
                resultModel.SourceTitle = sourceModel.DisplayText;

                var _urgencyID = entity.UrgencyID.ToString();
                var urgencyModel = _disputeInformationManage.GetAllDisUrgencyList().Where(p => p.Value == _urgencyID).FirstOrDefault();
                resultModel.UrgencyTitle = urgencyModel.DisplayText;

                var disputeTypeModel = _disputeTypeRepository.GetAll().Where(p => p.Id == entity.DisputeTypeID).FirstOrDefault();
                resultModel.DisputeTypeTitle = disputeTypeModel.Title;

                var currentProcess = _workFlow_ProcessRepository.GetAll().Where(p => p.Id == entity.Status).FirstOrDefault();
                if (currentProcess != null)
                    resultModel.CurrentProcessName = currentProcess.ProcessName;

                var fileModel = _fileRepository.GetAll().Where(p => p.Id == entity.FileID).FirstOrDefault();
                if (fileModel != null)
                    resultModel.ImgUrl = AppSetting.AppUrl + fileModel.Url;

                var EventDescImgModel = _fileRepository.GetAll().Where(p => p.Id == entity.EventDescImgID).FirstOrDefault();
                if (EventDescImgModel != null)
                    resultModel.EventDescImgUrl = AppSetting.AppUrl + EventDescImgModel.Url;

                disputeInformationEditDto = resultModel;
            }
            else
            {
                disputeInformationEditDto = new DisputeInformationAPPEditDto();
            }

            return disputeInformationEditDto;
        }

        /// <summary>
        /// 根据查询条件获取矛盾纠纷信息分页列表（超时一个月）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<DisputeInformationListDto>> GetPagedDisputeInformationsOverTimeAPPAsync(GetDisputeInformationIOSInput input)
        {
            var _pageIndex = Convert.ToInt32(input.PageIndex);
            var _pageSize = Convert.ToInt32(input.PageSize);

            var query = _disputeInformationRepositoryAsNoTrack;

            #region TODO:根据传入的参数添加过滤条件

            //TODO:根据传入的参数添加过滤条件

            #region 权限验证

            var userID = Convert.ToInt32(input.UserID);
            var userModel = _userRepository.FirstOrDefault(userID);
            GetRolesInput input_role = new GetRolesInput() { UserId = userID };
            var role = await _roleService.GetRolesByUserId(input_role);

            if (role.DisplayName == "乡镇网格管理员")
                query = query.Where(p => p.TownID == userModel.TownID || p.CreatorUserId == userID);
            else if (role.DisplayName == "社区网格管理员")
                query = query.Where(p => p.AreaID == userModel.AreaID || p.CreatorUserId == userID);
            else if (role.DisplayName == "村庄网格管理员")
                query = query.Where(p => p.VillageID == userModel.VillageID || p.CreatorUserId == userID);

            #endregion

            //上传人
            if (!string.IsNullOrWhiteSpace(input.UploadName))
                query = query.Where(p => p.UploadName == input.UploadName);

            #endregion

            var nowDate = DateTime.Now;

            query = query.Where(p => nowDate >= EntityFunctions.AddMonths(p.CreationTime, 1));

            var wfProcessList = (from wfProcess in _workFlow_ProcessRepository.GetAll()
                                 join wfTableName in _workFlow_TableNameRepository.GetAll()
                                 on wfProcess.FlowID equals wfTableName.Id
                                 where wfTableName.TableName == "DisputeInformations"
                                 select wfProcess).ToList();
            if (wfProcessList.Count > 0)
            {
                var endModel = wfProcessList.Where(p => p.ProcessType == "is_end").FirstOrDefault();
                var failModel = wfProcessList.Where(p => p.ProcessType == "is_fail").FirstOrDefault();
                query = query.Where(p => p.Status != endModel.Id && p.Status != failModel.Id);
            }

            var disputeInformationCount = await query.CountAsync();

            var disputeInformations = await query
            .OrderByDescending(p => p.Id)
            .Take(_pageSize * _pageIndex).Skip(_pageSize * (_pageIndex - 1))
            .ToListAsync();

            var areaList = _areaRepository.GetAll();
            var disputeTypeList = _disputeTypeRepository.GetAll();
            var disSourceList = GetAllDisSourceList();

            var workflowList = from wf_run in _workFlow_RunRepository.GetAll()
                               join wf_run_process in _workFlow_Run_ProcessRepository.GetAll()
                               on wf_run.Id equals wf_run_process.RunID
                               select new { wf_run.DetailID, wf_run_process.ProcessType };



            return new PagedResultDto<DisputeInformationListDto>(disputeInformationCount,
                disputeInformations.Select(item =>
                {
                    var dto = item.MapTo<DisputeInformationListDto>();

                    var sID = dto.SourceID.ToString();
                    var disSourceModel = disSourceList.Where(p => p.Value == sID).Select(p => new { p.DisplayText }).FirstOrDefault();
                    if (disSourceModel != null)
                        dto.SourceTitle = disSourceModel.DisplayText;

                    var disputeTypeModel = disputeTypeList.Where(p => p.Id == dto.DisputeTypeID).Select(p => new { p.Title }).FirstOrDefault();
                    if (disputeTypeModel != null)
                        dto.DisputeTypeTitle = disputeTypeModel.Title;

                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 根据查询条件获取矛盾纠纷信息分页列表
        /// </summary>
        public async Task<PagedResultDto<DisputeInformationListDto>> GetPagedDisputeInformationsIOSAsync(GetDisputeInformationIOSInput input)
        {
            var _pageIndex = Convert.ToInt32(input.PageIndex);
            var _pageSize = Convert.ToInt32(input.PageSize);
            var query = _disputeInformationRepositoryAsNoTrack;

            #region TODO:根据传入的参数添加过滤条件

            //TODO:根据传入的参数添加过滤条件

            #region 权限验证

            var userID = Convert.ToInt32(input.UserID);
            var userModel = _userRepository.FirstOrDefault(userID);
            GetRolesInput input_role = new GetRolesInput() { UserId = userID };
            var role = await _roleService.GetRolesByUserId(input_role);

            if (role.DisplayName == "乡镇网格管理员")
                query = query.Where(p => p.TownID == userModel.TownID || p.CreatorUserId == userID);
            else if (role.DisplayName == "社区网格管理员")
                query = query.Where(p => p.AreaID == userModel.AreaID || p.CreatorUserId == userID);
            else if (role.DisplayName == "村庄网格管理员")
                query = query.Where(p => p.VillageID == userModel.VillageID || p.CreatorUserId == userID);

            #endregion

            //上传人
            if (!string.IsNullOrWhiteSpace(input.UploadName))
                query = query.Where(p => p.UploadName == input.UploadName);

            #endregion

            var disputeInformationCount = await query.CountAsync();

            var disputeInformations = await query
            .OrderByDescending(p => p.Id)
            .Take(_pageSize * _pageIndex).Skip(_pageSize * (_pageIndex - 1))
            .ToListAsync();

            var areaList = _areaRepository.GetAll();
            var disputeTypeList = _disputeTypeRepository.GetAll();
            var disSourceList = GetAllDisSourceList();

            var workflowList = from wf_run in _workFlow_RunRepository.GetAll()
                               join wf_run_process in _workFlow_Run_ProcessRepository.GetAll()
                               on wf_run.Id equals wf_run_process.RunID
                               select new { wf_run.DetailID, wf_run_process.ProcessType };

            var workflowprocess = _workFlow_ProcessRepository.GetAll();

            return new PagedResultDto<DisputeInformationListDto>(disputeInformationCount,
                disputeInformations.Select(item =>
                {
                    var dto = item.MapTo<DisputeInformationListDto>();

                    var sID = dto.SourceID.ToString();
                    var disSourceModel = disSourceList.Where(p => p.Value == sID).Select(p => new { p.DisplayText }).FirstOrDefault();
                    if (disSourceModel != null)
                        dto.SourceTitle = disSourceModel.DisplayText;

                    var disputeTypeModel = disputeTypeList.Where(p => p.Id == dto.DisputeTypeID).Select(p => new { p.Title }).FirstOrDefault();
                    if (disputeTypeModel != null)
                        dto.DisputeTypeTitle = disputeTypeModel.Title;

                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    var wfList = workflowList.Where(p => p.DetailID == dto.Id && p.ProcessType == "is_end").ToList();
                    if (wfList.Count > 0)
                        dto.ShowMenu = false;
                    else
                        dto.ShowMenu = true;

                    var currentProcess = workflowprocess.Where(p => p.Id == dto.Status).FirstOrDefault();
                    if (currentProcess != null)
                        dto.CurrentProcessName = currentProcess.ProcessName;

                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 新增矛盾纠纷信息
        /// </summary>
        public virtual async Task<DisputeInformationEditDto> CreateDisputeInformationIOSAsync(DisputeInformationIOSEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<DisputeInformation>();

            #region 获取发起节点ID
            //获取发起节点ID
            var query = from process in _workFlow_ProcessRepository.GetAll()
                        join table in _workFlow_TableNameRepository.GetAll()
                        on process.TableID equals table.Id
                        where table.TableName == "DisputeInformations"
                        select new { process.Id, process.ProcessOrder, process.TableID, process.FlowID };

            var wf_ProcessModel = query.OrderBy(p => p.ProcessOrder).FirstOrDefault();
            #endregion

            entity.Status = Convert.ToInt32(wf_ProcessModel.Id);//赋值发起节点ID

            //转换坐标系
            double oldX = 0, oldY = 0;
            double.TryParse(entity.XPoint, out oldX);
            double.TryParse(entity.YPoint, out oldY);


            var newPoint = PositionHelper.bd09_To_Gps84(oldY, oldX);
            entity.XPoint = newPoint.getWgLon().ToString();
            entity.YPoint = newPoint.getWgLat().ToString();

            //先执行新增纠纷操作
            entity.Id = await _disputeInformationRepository.InsertAndGetIdAsync(entity);

            //添加工作流
            _workFlowManage.AuditStart(Convert.ToInt32(entity.Id), Convert.ToInt32(wf_ProcessModel.Id), "发起一个纠纷事件", Convert.ToInt32(wf_ProcessModel.Id), wf_ProcessModel.FlowID);

            return entity.MapTo<DisputeInformationEditDto>();
        }

        /// <summary>
        /// 编辑矛盾纠纷信息
        /// </summary>
        public virtual async Task UpdateDisputeInformationIOSAsync(DisputeInformationIOSEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            input.MapTo(entity);

            #region 获取当前节点的下一节点
            //获取当前节点的下一节点
            var wfProcess = _workFlow_ProcessRepository;
            var wf_ProcessModel = wfProcess.FirstOrDefault(entity.Status);
            #endregion

            #region 获取FlowID
            //获取FlowID
            var query = from process in _workFlow_ProcessRepository.GetAll()
                        join table in _workFlow_TableNameRepository.GetAll()
                        on process.TableID equals table.Id
                        where table.TableName == "DisputeInformations"
                        select new { process.Id, process.ProcessOrder, process.TableID, process.FlowID };
            var wfProcessNewModel = query.FirstOrDefault();
            #endregion

            if (input.ProcessContent == "进行纠纷事件失败处理" || input.ProcessContent == "进行纠纷事件拒签处理" || input.ProcessContent == "进行纠纷事件未履行")
            {
                var failModel = wfProcess.GetAll().Where(p => p.FlowID == wfProcessNewModel.FlowID && p.ProcessType == "is_fail").FirstOrDefault();

                //添加工作流
                _workFlowManage.AuditStart(Convert.ToInt32(entity.Id), entity.Status, input.ProcessContent, Convert.ToInt32(failModel.Id), wfProcessNewModel.FlowID);
                entity.Status = Convert.ToInt32(failModel.Id);//赋值失败节点ID
            }
            else
            {
                //添加工作流
                _workFlowManage.AuditStart(Convert.ToInt32(entity.Id), entity.Status, input.ProcessContent, Convert.ToInt32(wf_ProcessModel.ProcessTo), wfProcessNewModel.FlowID);
                entity.Status = Convert.ToInt32(wf_ProcessModel.ProcessTo);//赋值下一节点ID
            }

            await _disputeInformationRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除矛盾纠纷信息
        /// </summary>
        public async Task DeleteDisputeInformationIOSAsync(EntityDto<string> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            var id = Convert.ToInt32(input.Id);
            await _disputeInformationRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 编辑矛盾纠纷信息（无流程）
        /// </summary>
        public virtual async Task UpdateDisputeInformationNoWorkFlowIOSAsync(DisputeInformationIOSEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            input.MapTo(entity);

            await _disputeInformationRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 分流
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task ShuntIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            entity.HandleTownID = Convert.ToInt32(input.HandleTownID);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件分流";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 现场调处
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task MediationIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件现场调处";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 意见
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SuggessIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            entity.SuggestionDesc = input.SuggestionDesc;
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            await UpdateDisputeInformationNoWorkFlowIOSAsync(model);
        }

        /// <summary>
        /// 成功
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SuccessIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件成功处理";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 失败
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task FailIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件失败处理";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 上传协议书
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UploadAgreementIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.FileID = input.FileID;
            model.Agreement = input.Agreement;
            model.ProcessContent = "进行纠纷事件进行上传协议书";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 拒签
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task RefuseIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件拒签处理";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 履行
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task PerformIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件履行";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 未履行
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UnfulfilledIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件未履行";
            await UpdateDisputeInformationIOSAsync(model);
        }

        /// <summary>
        /// 结案归档
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task ConfirmIOS(FenLiuIOSEditDto input)
        {
            var id = Convert.ToInt32(input.Id);
            var entity = await _disputeInformationRepository.GetAsync(id);
            var model = entity.MapTo<DisputeInformationIOSEditDto>();
            model.ProcessContent = "进行纠纷事件结案归档";
            await UpdateDisputeInformationIOSAsync(model);
        }

        #endregion

    }
}
